package com.ti.shangou.controller.pages.back.upload;

import com.ti.shangou.controller.BaseController;
import com.ti.shangou.pojo.dto.ResponseDTO;
import com.ti.shangou.service.impl.ImgCacheServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者：田宝山
 * 日期：2020/6/4
 */
@Controller
@RequestMapping("/pages/back/upload")
public class UploadController extends BaseController {
    @Resource
    ImgCacheServiceImpl imgCacheService;

    @RequestMapping("uploadFiles")
    @ResponseBody
    public Object uploadFiles (MultipartHttpServletRequest request){
        boolean res =false;
        // 获得文件集合
        Collection<MultipartFile> values = request.getFileMap().values();
        StringBuffer buffer = new StringBuffer();
        String uploadPath="/upload/";
        String dir = request.getParameter("dir");

        // 如果自己定义了目录
        if (!StringUtils.isEmpty(dir)){
            if (dir.endsWith("/")){
                uploadPath += dir;
            }else {
                uploadPath += dir + "/";
            }
        }
        for (MultipartFile f:values){
            String s = saveFile(f, uploadPath); // 保存的路径
            if (!StringUtils.isEmpty(s)){
                if (imgCacheService.addCache(s)){
                    res = true;
                    buffer.append(s).append(",");
                }
            }
        }
        if (buffer.length()>0){
            buffer.delete(buffer.length()-1,buffer.length());
        }
        /*Map map = new HashMap();
        map.put("data",buffer.toString());
        map.put("msg","上传成功");
        map.put("res",res);*/
        return ResponseDTO.ok("上传成功", buffer.toString());
    }

}
